<template>
  <div class="container">
    <div class="app-container">
      <el-button type="primary" style="padding:10px" @click="showDialog = true">新增角色</el-button>
      <el-table
        :data="tableData"
        style="width: 100%;margin: 20px auto"
      >
        <el-table-column
          prop="name"
          label="角色"
          width="200"
          align="center"
        >
          <template v-slot="{row}">
            <el-input v-if="row.isEdit" v-model="row.editRow.name" size="mini" />
            <span v-else>{{ row.name }}</span>
          </template>
        </el-table-column>
        <el-table-column
          prop="state"
          label="状态"
          width="200"
          align="center"
        >
          <template slot-scope="scope">
            <span v-if="!scope.row.isEdit">
              <span v-if="scope.row.state === 1">已启用</span>
              <span v-else-if="scope.row.state === 0">已禁用</span>
              <span v-else>无</span>
            </span>
            <el-switch v-else v-model="scope.row.editRow.state" size="mini" :active-value="1" :inactive-value="0" />
          </template>

        </el-table-column>

        <el-table-column
          prop="description"
          label="描述"
          align="center"
        >
          <template v-slot="{row}">
            <el-input v-if="row.isEdit" v-model="row.editRow.description" size="mini" type="textarea" />
            <span v-else>{{ row.description }}</span>
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center">
          <template v-slot="{ row }">
            <template v-if="row.isEdit">
              <!-- 编辑状态 -->
              <el-button type="primary" size="mini" @click="save(row)">确定</el-button>
              <el-button size="mini" @click="row.isEdit = false">取消</el-button>
            </template>
            <template v-else>
              <!-- 非编辑状态 -->
              <el-button size="mini" type="text" @click="btnPermission(row.id)">分配权限</el-button>
              <el-button size="mini" type="text" @click="edit(row)">编辑</el-button>
              <el-button size="mini" type="text" @click="del(row)">删除</el-button>
            </template>
          </template>
        </el-table-column>
      </el-table>
      <el-row type="flex" style="height:60px" align="middle" justify="end">
        <!-- 放置分页组件 -->
        <el-pagination layout="prev, pager, next" small :total="total" :current-page="currentPage" :page-size="pageSize" @current-change="currentChange" />
      </el-row>
      <el-dialog width="500px" title="新增角色" :visible.sync="showDialog" @close="close">
        <!-- 表单内容 -->
        <el-form ref="roleRef" label-width="120px" :model="roleform" :rules="rules">
          <el-form-item label="角色名称" prop="name">
            <el-input v-model="roleform.name" style="width:300px" size="mini" />
          </el-form-item>
          <el-form-item label="启用">
            <el-switch v-model="roleform.state" size="mini" :active-value="1" :inactive-value="0" />
          </el-form-item>
          <el-form-item label="角色描述" prop="description">
            <el-input v-model="roleform.description" type="textarea" :rows="3" style="width:300px" size="mini" />
          </el-form-item>
          <el-form-item>
            <el-row type="flex" justify="center">
              <el-col :span="12">
                <el-button type="primary" size="mini" @click="submit">确定</el-button>
                <el-button size="mini" @click="close">取消</el-button>
              </el-col>
            </el-row>
          </el-form-item>
        </el-form>
      </el-dialog>
      <el-dialog width="500px" title="分配权限" :visible.sync="showPermissionDialog">
        <el-tree
          ref="permTree"
          :data="permissionData"
          show-checkbox
          node-key="id"
          :props="defaultProps"
          default-expand-all
          :default-checked-keys="permIds"
          check-strictly
        />
        <el-row slot="footer" type="flex" justify="center">
          <el-col>
            <el-button type="primary" size="mini" @click="btnPermissionOK">确定</el-button>
            <el-button size="mini" @click="showPermissionDialog = false">取消</el-button>
          </el-col>
        </el-row>
      </el-dialog>
    </div>

  </div>
</template>
<script>
import { addRole, deleteRole, getRoleList, updateRole, getRole, assignPerm } from '@/api/role'
import { getpermissionList } from '@/api/permission'
import { transListToTreeData } from '@/utils'
export default {
  name: 'Role',
  data() {
    return {
      tableData: [],
      currentPage: 1,
      total: 0,
      pageSize: 5,
      showDialog: false,
      roleform: {
        name: '',
        state: 0,
        description: ''
      },
      roleRef: null,
      rules: {
        name: [{ required: true, message: '请输入角色名称', trigger: 'blur' },
          { min: 2, max: 10, message: '长度在 2 到 10 个字符', trigger: 'blur' }
        ],
        description: [
          { required: true, message: '请输入角色描述', trigger: 'blur' },
          { min: 2, max: 10, message: '长度在 2 到 10 个字符', trigger: 'blur' }
        ]
      },
      showPermissionDialog: false,
      permissionData: [],
      defaultProps: {
        label: 'name',
        children: 'children'
      },
      currentUserId: null,
      permIds: []
    }
  },
  created() {
    this.getRoleList()
  },
  methods: {
    currentChange(val) {
      console.log('当前页码', val)
      this.currentPage = val
      this.getRoleList()
    },
    async getRoleList() {
      const res = await getRoleList(this.currentPage, this.pageSize)
      this.total = res.total
      this.tableData = res.rows
      this.tableData.forEach(item => {
        this.$set(item, 'isEdit', false)
        this.$set(item, 'editRow', {
          name: item.name,
          description: item.description,
          state: item.state
        })
      })
      console.log(res)
    },
    close() {
      this.showDialog = false
      this.$refs.roleRef.resetFields()
      this.roleform = {
        name: '',
        state: 0,
        description: ''
      }
    },
    async submit() {
      await this.$refs.roleRef.validate()
      await addRole(this.roleform)
      this.$message.success('新增成功')
      this.close()
      const lastPage = Math.ceil((this.total + 1) / this.pageSize)
      this.currentPage = lastPage
      this.getRoleList()
    },
    edit(row) {
      row.isEdit = true
      // 更新缓存数据
      row.editRow.name = row.name
      row.editRow.state = row.state
      row.editRow.description = row.description
    },
    async  save(row) {
      console.log(row)
      if (row.editRow.name && row.editRow.description) {
        await updateRole({ ...row.editRow, id: row.id })
        this.$message.success('角色更新成功')
        Object.assign(row, {
          ...row.editRow,
          isEdit: false
        })
        console.log('更新之后的row', row)
      } else {
        this.$message.error('角色和描述不能为空')
      }
    },
    del(row) {
      console.log(row)
      this.$confirm('确认删除该角色吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async() => {
        await deleteRole(row.id)
        this.$message({
          type: 'success',
          message: '删除成功!'
        })
        if (this.tableData.length === 1) {
          this.currentPage--
        }
        this.getRoleList()
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        })
      })
    },
    async btnPermission(id) {
      this.currentUserId = id
      const { permIds } = await getRole(id)
      this.permIds = permIds
      const res = await getpermissionList()
      this.permissionData = transListToTreeData(res, 0)
      console.log('permIds', permIds)
      this.showPermissionDialog = true
    },
    async btnPermissionOK() {
      await assignPerm(this.currentUserId, this.$refs.permTree.getCheckedKeys())
      this.$message.success('分配权限成功')
      this.showPermissionDialog = false
    }

  }
}
</script>
<style lang="scss" scoped>
</style>

